﻿using System.IO;
using System.Text;
using HorseRaceRe.Code.Helpers;
using HorseRaceRe.Code.Models;
using XQColorful.SDK;
using XQColorful.SDK.EventArgs;
using XQColorful.SDK.Interface;
using XQColorful.SDK.Models;

namespace HorseRaceRe.Code.Events
{
    public class EventJoinRace : IPluginEvent
    {
        public XQEventType EventType => XQEventType.Group;


        public void Process(XQEventArgs _e)
        {
            var e = new GroupMsgEventArgs(_e);

            if (e.Message.StartsWith("加入赛马"))
            {
                var msg = new StringBuilder();

                if (App.GroupGrounds.ContainsKey(e.FromGroup))
                {
                    var horsename = e.Message.TrimStart("加入赛马".ToCharArray()).Trim();
                    if (horsename == "")
                    {
                        e.SendMsg(XQCode.At(e.FromQQ) + "格式错误:加入赛马+emoji表情");
                        return;
                    }

                    //已经有比赛了
                    //var hb = HorseBase.FromFile(PathHelper.GetHorseBase( e.FromQQ));
                    if (horsename != "")
                    {
                        var hb = new HorseBase()
                        {
                            Name = horsename,
                        };
                        if (App.GroupGrounds[e.FromGroup].AddHorse(hb, e.FromQQ))
                        {
                            msg.AppendLine(XQCode.At(e.FromQQ) + "加入成功!");
                            var groundinfo = App.GroupGrounds[e.FromGroup];
                            msg.AppendLine($"赛马场选手数量{groundinfo.Horses.Count - 1}->{groundinfo.Horses.Count}");
                            msg.AppendLine(
                                $"{(groundinfo.Horses.Count >= App.AppSet.MinJoin ? "最低开赛数量达成" : "还不足最低开赛马数!")}");
                            msg.AppendLine(
                                $"最大还剩{App.AppSet.MaxJoin - groundinfo.Horses.Count}空位");
                        }

                        if (App.AppSet.MaxJoin - App.GroupGrounds[e.FromGroup].Horses.Count == 0)
                        {
                            EventStartRace.StartRace(e, e.FromGroup);
                        }
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    msg.AppendLine("本群还未开始赛马比赛!");
                }

                e.SendMsg(msg.ToString());
                return;
            }
        }
    }
}